package com.msdemo.goods.controller;

import java.util.HashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.msdemo.goods.GoodsServiceProvider;
import com.msdemo.goods.service.client.OrderServiceClient;
import com.msdemo.goods.util.ServiceInfoUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

/**
* @comments 商品Controller
* @author zg
* @date 2017年9月28日
*/
@RestController
@RequestMapping("/goods/")
@PropertySource("classpath:config.properties")
public class GoodsController {
	private Logger logger = LogManager.getLogger(this.getClass());
	
	@Value("${googds.service.instance}") 
	private String instance;
	
	@Autowired
	private OrderServiceClient orderServiceClient;
	
	@RequestMapping("buy")
	@HystrixCommand(fallbackMethod="buyFallback")
	public String buy( 
			@RequestParam(name="userName", required = true) String userName,
			@RequestParam(name="goodsId", required = true) String goodsId) {
		
		logger.info("用户“{}”购买了商品，商品ID【{}】，扣减库存...", userName, goodsId);
		//TODO 扣减库存操作...
		
		logger.info("调用订单服务生成订单...");
		String result = orderServiceClient.createOrder(userName, goodsId);
		if("success".equals(result)) {
			logger.info("订单创建成功！");
		}else {
			logger.info("订单创建失败");
		}
		
		return result;
	}
	
	public String buyFallback(@RequestParam(name="userName", required = true) String userName,
							  @RequestParam(name="goodsId", required = true) String goodsId) {
		logger.error("Hystrix:用户“{}”，商品ID【{}】.", userName, goodsId);
		return "buyFallback!";
	}
	
	@RequestMapping("show")
	public String show() {
		
		logger.info("商品服务（实例{}）", ServiceInfoUtil.getPort());
		
		return "success-" + ServiceInfoUtil.getPort();
	}
	
}
